package br.com.lumis.ims.service.cloud.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

import lumis.portal.PortalException;
import lumis.portal.UnexpectedException;
import lumis.portal.dao.jdbc.ITransactionJdbc;
import lumis.util.ITransaction;
import br.com.lumis.ims.service.cloud.model.UserIMS;
import br.com.lumis.ims.service.cloud.util.ImsRequestParameters;

public class UserDAO 
{
	private static final String QUERY_UPDATE_LUM_USERID ="update ims_user set lumUserId = ? where name = ?";
	private static final String QUERY_GET_BY_LUMUSERID ="select * from ims_user where lumUserId = ?";
	
	public void updateLumUserId(String name, String lumUserId, ITransaction transaction) throws PortalException{	
		try
		{
			ITransactionJdbc daoTransactionJdbc = (ITransactionJdbc) transaction;
			Connection connection = daoTransactionJdbc.getConnection();

			PreparedStatement statement = connection.prepareStatement(QUERY_UPDATE_LUM_USERID);
			try
			{
				statement.setString(1, lumUserId);
				statement.setString(2, name);
				statement.executeUpdate();
			}
			finally
			{
				statement.close();
			}

		}
		catch (PortalException e)
		{
			throw e;
		}
		catch (Exception e)
		{
			throw new UnexpectedException(e);
		}

	}
	
	
	public UserIMS getUserIMS(String id, ITransaction transaction) throws PortalException{
		UserIMS userims = null;
		try
		{					
			ITransactionJdbc daoTransactionJdbc = (ITransactionJdbc) transaction;
			Connection connection = daoTransactionJdbc.getConnection();

			PreparedStatement statement = connection.prepareStatement(QUERY_GET_BY_LUMUSERID);
			try{
				statement.setString(1, id);
				ResultSet resultSet = statement.executeQuery();
				try{
					if(resultSet.next()){
						userims = new UserIMS();
						userims.setId(resultSet.getString( ImsRequestParameters.ID));
						userims.setName(resultSet.getString(ImsRequestParameters.NAME));												
						userims.setAccesskey(resultSet.getString(ImsRequestParameters.ACCESSKEY));
						userims.setSecretkey(resultSet.getString(ImsRequestParameters.SECRETKEY));
											
						return userims;
					}
				}
				finally{
					resultSet.close();
				}
			}
			finally{
				statement.close();
			}						
		}
		catch (PortalException e){
			throw e;
		}
		catch (Exception e){
			throw new UnexpectedException(e);
		}
		
		return userims;
	}
}
